const cloud = require('wx-server-sdk');
var request = require('request');
var MD5 = require('md5');
const DISABLESERVICE = 0;
const APIKey = '';
const SecretKey = '';
const PlatformId = '';
const Secret = '';
const TelX = '';
const TemplateId = 100268;
const VoiceNumber = '';

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
exports.main = async (event, context) => {
  console.log(event)
  switch (event.action) {
    case 'bindAXB': {
      return bindAXB(event)
    }
    case 'sendVoiceCode': {
      return sendVoiceCode(event)
    }
    default: {
      return
    }
  }
}
function buildApiAuth() {
  var TIME = new Date().getTime();
  var signStr = MD5(APIKey + SecretKey + TIME);
  var jsonStr = JSON.stringify({
    "apiKey": APIKey,
    "time": TIME,
    "sign": signStr
  });
  var apiAuthBuffer = new Buffer.from(jsonStr);
  var apiAuth = apiAuthBuffer.toString('base64');
  return apiAuth;
}
function buildApiAccessCode(){
  var jsonStr = JSON.stringify({
    "platformId": PlatformId,
    "secret": Secret
  });
  var apiAccessCodeBuffer = new Buffer.from(jsonStr);
  var apiAccessCode = apiAccessCodeBuffer.toString('base64');
  return apiAccessCode;
}

//绑定小号
async function bindAXB(event) {
  let resp = {code:0,msg:'',data:''};
  let callNum = '';
  let bOpenid = event.bOpenid;
  let userMobile = '';
  let userInfo = await getUserInfo();
  if (userInfo && userInfo.mobile) {
    userMobile = userInfo.mobile;
  } else {
    resp.code = 0;
    resp.msg = '未绑定手机号';
    return resp;
  }

  let userB = await getUserInfo(bOpenid)
  if (userB && userB.mobile) {
    callNum = userB.mobile;
  } else {
    resp.code = 0;
    resp.msg = '未绑定手机号';
    return resp;
  }

  const hasBalanceTime = await checkBalanceTime();

  if (!hasBalanceTime){
    resp.code = 0;
    resp.msg = '剩余时间不足';
    return resp;
  }

  if (DISABLESERVICE) {
    resp.code = 0;
    resp.msg = '系统维护中';
    return resp;
  }

  const apiurl ='http://dev.cmccopen.cn/api/v1/midb/bind/ST0004';
  const apiAuth = buildApiAuth();
  const apiAccessCode = buildApiAccessCode();
  const telA = userMobile;
  const telB = callNum;
  const telX = TelX;
  const param = {
    "telA": telA,
    "telB": telB,
    "telX": '86'+telX,
    "expiration": 60,
    "record": "1",
    "gnFlag": "11"
  }
  console.log('apiAccessCode:', apiAccessCode);
  console.log('apiAuth:', apiAuth);
  console.log('param:', param);
  let apiResp = await postUrl(apiurl, param);
  
  console.log("bindAXB Resp:", apiResp);   
  
  //{ resultCode: 1001, resultMsg: '绑定关系冲突' }
  //{ resultCode: 1001, resultMsg: '绑定关系已存在' }
  if (apiResp){
    let axblog = apiResp;
    axblog.telA = telA;
    axblog.telB = telB;
    axblog.telX = telX;
    axblog.createtime = new Date().getTime();
    axblog.openid = userInfo.openid;
    await saveAxb(axblog);
    if (apiResp.resultCode == 1001 && apiResp.resultMsg =='绑定关系已存在'){
      await delayAXB(telA, telB, telX);//延期60S
      apiResp.resultCode = 200;//解绑定
    }
    switch (apiResp.resultCode){
      case 200:
          resp.code = 1;
          resp.msg = "绑定成功";
          resp.data = telX;
        break;
      case 1001:
        resp.code = 0;
        resp.msg = "操作频繁，请稍后再试";//60s后自动解绑
        resp.data = apiResp;
        break;
      default:
        resp.code = 0;
        resp.msg = "系统维护中";
        resp.data = apiResp;
    }
  }
  return resp;
}

//延期绑定关系
async function delayAXB(telA,telB,telX) {
  console.log('delayAXB', telA, telB, telX);
  let bindId ='';
  const dbret = await db.collection('axb').where({
    telA: telA,
    telB: telB,
    telX: telX,
    resultCode:200
  }).limit(1).orderBy('createtime', 'desc').get();//获取上次绑定的bindId
  console.log('dbret', dbret);
  const bindData = dbret.data[0];
  if (bindData && bindData.bindId){
    bindId = bindData.bindId;
  }
  if (!bindId){
    console.log('delayAXB ERROR，dbret：',dbret);
    return false;
  }
  const apiurl = 'http://dev.cmccopen.cn/api/v1/midb/delay/001';
  const apiAuth = buildApiAuth();
  const apiAccessCode = buildApiAccessCode();
  const param = {
    "bindId": bindId,
    "delta": "60"
  }
  console.log('apiAccessCode:', apiAccessCode);
  console.log('apiAuth:', apiAuth);
  console.log('param:', param);
  let apiResp = await postUrl(apiurl, param);
  
  console.log("delayAXB Resp:",apiResp);
  if (apiResp && apiResp.resultCode==200){
    return true;
  }else{
    return false;
  }
}

async function getUserInfo(openid) {
  if (!openid){
    openid = cloud.getWXContext().OPENID;
  }
  const dbret = await db.collection('user').where({
    openid: openid
  }).get();
  console.log('getUserInfo dbret:', dbret);
  return dbret.data[0];
}

async function checkBalanceTime() {
  return true;
  const wxContext = cloud.getWXContext();
  let lastBalanceLog = await db.collection('balance').where({
    openid: wxContext.OPENID
  }).limit(1).orderBy('createtime', 'desc').get();
  if (lastBalanceLog && lastBalanceLog.errMsg && lastBalanceLog.errMsg == 'collection.get:ok') {
    let lastBalanceData = lastBalanceLog.data[0];
    if (lastBalanceData && lastBalanceData.totalblancetime > 0) {
      return true;
    }
  } 
  return false;
}

async function postUrl(url,body) {
  const apiAuth = buildApiAuth();
  const apiAccessCode = buildApiAccessCode();
  const headers = {
    "Content-Type": "application/json",
    "Authorization": apiAuth,
    "AccessCode": apiAccessCode
  }
  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: "POST",
      json: true,
      headers: headers,
      body: body
    }, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        try {
          resolve(body)
        } catch (e) {
          reject()
        }
      }
    })
  })
}


async function saveAxb(data) {
  const dbret =  await db.collection('axb').add({
    data: data
  })
  if (dbret && dbret.errMsg && dbret.errMsg == "collection.add:ok") {
    return true;
  }else{
    return false;
  }
}

//语音验证码
async function sendVoiceCode(event) {
  let resp = { code: 0, msg: '', data: '' };
  let callNum = '';
  if (event.callNum && event.callNum.length == 11) {
    callNum = event.callNum;
  } else {
    resp.code = 0;
    resp.msg = '请输入正确号码';
    return resp;
  }

  // if (DISABLESERVICE) {
  //   resp.code = 0;
  //   resp.msg = '系统维护中';
  //   return resp;
  // }

  const apiurl = 'http://dev.cmccopen.cn/api/v1/voice/voiceNotify';
  const apiAuth = buildApiAuth();
  const apiAccessCode = buildApiAccessCode();
  const templateId = TemplateId;
  const voiceNumber = VoiceNumber;

  const param = {
    "voiceNumber": voiceNumber,
    "to": callNum,
    "playTimes": 3,
    "templateId": templateId,
    "templateParameter": {
      "code": ',1,2,3,4'
    },
    "respUrl": "http://api.pet.t4kj.com/cmcc?action=notice"
  }
  console.log('apiAccessCode:', apiAccessCode);
  console.log('apiAuth:', apiAuth);
  console.log('param:', param);
  let apiResp = await postUrl(apiurl, param);

  console.log("sendVoiceCode Resp:", apiResp);

  if (apiResp) {
    if (apiResp.resultCode == 200 ) {
      resp.code = 1;
      resp.msg = "发送成功";
      resp.data = '';
    }else{
      resp.msg = "发送失败";
      resp.data = apiResp;
    }
  }
  return resp;
}